package com.lemon.core.web.util;

import com.lemon.core.base.constant.GlobalConstants;
import com.lemon.core.base.util.CheckUtils;
import org.slf4j.MDC;

import javax.servlet.http.HttpServletRequest;

/**
 * @author pan
 * @since 2020-02-28
 */
public class TracerUtils {

    private TracerUtils() {
    }

    /**
     * 从header和参数中获取traceId
     * 从前端传入数据
     *
     * @param request 　HttpServletRequest
     * @return traceId
     */
    public static String getTraceId(HttpServletRequest request) {
        String traceId = request.getParameter(GlobalConstants.CLOUD_TRACE_ID);
        if (CheckUtils.isBlank(traceId)) {
            traceId = request.getHeader(GlobalConstants.CLOUD_TRACE_ID);
        }
        return traceId;
    }

    /**
     * 传递traceId至MDC
     *
     * @param traceId 　跟踪ID
     */
    public static void mdcTraceId(String traceId) {
        if (CheckUtils.isNotBlank(traceId)) {
            MDC.put(GlobalConstants.LOG_TRACE_ID, traceId);
        }
    }
}
